package com.rgs.ssm.dao;

import com.rgs.ssm.domain.Role;
import com.rgs.ssm.domain.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @create 2021-02-18 18:54
 **/
public interface IUserDao {

    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.rgs.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findByUsername(String username);

    /**
     * 保存（添加）用户的信息
     * @param userInfo
     */
    @Insert("insert into users(email,username,password,phoneNum,status) values (#{email},#{username},#{password},#{phoneNum},#{status})")
    void saveUser(UserInfo userInfo);

    /**
     * 删除
     * @param id
     */
    @Delete("delete from users where id = #{id}")
    void delete(Integer id);

    /**
     * 修改
     * @param userInfo
     */
    @Update("update users set email=#{email},username=#{username},password=#{password},phoneNum=#{phoneNum},status=#{status} where id = #{id}")
    void update(UserInfo userInfo);


    /**
     * 查询所有的用户信息
     * @return
     */
    @Select("select * from users")
    List<UserInfo> findAll();

    /**
     * 根据用户的id，查询对应的用户信息
     * @param userId
     * @return
     */
    @Select("select * from users where id = #{userId}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(select = "com.rgs.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findById(Integer userId);

    /**
     * 根据用户的id，查询出用户没有的角色
     * @param userId
     * @return
     */
    @Select("select * from role where id not in (select roleId from users_role where userId =#{userId})")
    List<Role> findByIdOtherRole(Integer userId);

    /**
     * 给用户添加角色（users_role表）
     * @param userId
     * @param roleId
     */
    @Insert("insert into users_role (userId,roleId) values (#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") Integer userId,@Param("roleId") Integer roleId);


}
